package com.zheng.oa.admin.controller.hr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Maps;
import com.zheng.common.base.BaseController;
import com.zheng.common.util.CamelUnderlineConverter;
import com.zheng.hr.dao.model.HrMeeting;
import com.zheng.hr.dao.model.HrMeetingUser;
import com.zheng.hr.rpc.api.HrMeetingService;
import com.zheng.hr.rpc.api.HrMeetingUserService;
import com.zheng.oa.common.constant.OaResult;
import com.zheng.oa.common.constant.OaResultConstant;
import com.zheng.oa.common.constant.enums.OaStatus;
import com.zheng.oa.common.exception.OaException;
import com.zheng.upms.rpc.api.UpmsApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2017/11/16
 * Time: 11:17
 */
@Controller
@Api(value = "会议管理", description = "会议管理")
@RequestMapping("/oa/hr/meeting")
public class HrMeetingController extends BaseController {
    @Autowired
    private HrMeetingService meetingService;
    @Autowired
    private HrMeetingUserService meetingUserService;
    @Autowired
    private UpmsApiService apiService;

    @ApiOperation(value = "会议管理首页")
    @RequiresPermissions("oa:hr:meeting:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        return "/manage/hr/meeting/index.jsp";
    }

    @ApiOperation(value = "会议列表")
    @RequiresPermissions("oa:hr:meeting:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(@RequestParam(required = false, defaultValue = "1", value = "pageNumber") int pageNumber,
                       @RequestParam(required = false, defaultValue = "10", value = "pageSize") int pageSize,
                       @RequestParam(required = false, value = "sortName") String sortName,
                       @RequestParam(required = false, value = "sortOrder") String sortOrder,
                       @RequestParam(required = false, value = "beginDate") String beginDate,
                       @RequestParam(required = false, value = "endDate") String endDate) {
        Wrapper<HrMeeting> wrapper = new EntityWrapper<>();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            if (sortOrder.equalsIgnoreCase("asc")) {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), true);
            } else {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), false);
            }
        }
        if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)) {
            wrapper.where("begin_time  between'" + beginDate + "'and'" + endDate + "'");
        }
        wrapper.where("status!=" + HrMeeting.DELETE);
        wrapper.orderBy("begin_time");
        wrapper = apiService.dataScopeFilter(wrapper, getUsername());
        Page<Map<String, Object>> page = meetingService.selectMapsPage(new Page<>(pageNumber, pageSize), wrapper);
        List<Map<String, Object>> maps = page.getRecords();
        for (Map<String, Object> meeting : maps) {
            String state = "正常";
            int status = Integer.parseInt(meeting.get("status").toString());
            if (status == HrMeeting.CANCEL) {
                state = "已取消";
            } else if (status == HrMeeting.FINISH) {
                state = "已结束";
            }
            meeting.put("state", state);
        }
        int total = meetingService.selectCount(wrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", maps);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "新增会议")
    @RequiresPermissions("oa:hr:meeting:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {
        return "/manage/hr/meeting/create.jsp";
    }

    @ApiOperation(value = "新增会议")
    @RequiresPermissions("oa:hr:meeting:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(@RequestBody HrMeeting meeting) throws Exception {
        try {
            meetingService.insertMeeting(meeting, getUsername());
        } catch (OaException e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "修改会议")
    @RequiresPermissions("oa:hr:meeting:update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(Integer id, Model model) {
        HrMeeting meeting = meetingService.selectById(id);
        EntityWrapper<HrMeetingUser> meetingUserEntityWrapper = new EntityWrapper<>();
        meetingUserEntityWrapper.where("meeting_id=" + meeting.getId());
        List<HrMeetingUser> meetingUsers = meetingUserService.selectList(meetingUserEntityWrapper);
        model.addAttribute("meetingUsers", JSONObject.toJSON(meetingUsers));
        model.addAttribute("meeting", meeting);
        return "/manage/hr/meeting/update.jsp";
    }

    @ApiOperation(value = "修改会议纪要")
    @RequiresPermissions("oa:hr:meeting:update")
    @RequestMapping(value = "/updateSummary", method = RequestMethod.GET)
    public String updateSummary(Integer id, Model model) {
        HrMeeting meeting = meetingService.selectById(id);
        model.addAttribute("meeting", meeting);
        model.addAttribute("status",HrMeeting.FINISH);
        return "/manage/hr/meeting/updateSummary.jsp";
    }

    @ApiOperation(value = "修改会议")
    @RequiresPermissions("oa:hr:meeting:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@RequestBody HrMeeting meeting) {
        try {
            meetingService.updateMeeting(meeting);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "删除会议")
    @RequiresPermissions("oa:hr:meeting:delete")
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
        try {
            meetingService.updateMeetingsStatue(ids,HrMeeting.DELETE);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "取消会议")
    @RequiresPermissions("oa:hr:meeting:delete")
    @RequestMapping(value = "/cancelMeeting/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object cancel(@PathVariable("ids") String ids) {
        try {
            meetingService.updateMeetingsStatue(ids,HrMeeting.CANCEL);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }
    @ApiOperation(value = "恢复会议")
    @RequiresPermissions("oa:hr:meeting:update")
    @RequestMapping(value = "/recoveryMeeting/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object recovery(@PathVariable("ids") String ids) {
        try {
            meetingService.updateMeetingsStatue(ids,HrMeeting.NORMAL);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }
    @RequiresPermissions("oa:hr:meeting:update")
    @RequestMapping(value = "/updateMeetingUsers", method = RequestMethod.GET)
    public String updateMeetingUsers(Integer id, Model model) {
        List<Map<String, Object>> meetingUsers = meetingUserService.selectMeetingUsersById(id);
        model.addAttribute("meetingUsers", JSON.toJSON(meetingUsers));
        return "/manage/hr/meeting/updateMeetingUsers.jsp";
    }

    @RequiresPermissions("oa:hr:meeting:update")
    @RequestMapping(value = "/updateMeetingUsers", method = RequestMethod.POST)
    @ResponseBody
    public Object updateMeetingUsers(@RequestBody JSONArray meetingUserList) {
        List<HrMeetingUser> meetingUsers = meetingUserList.toJavaList(HrMeetingUser.class);
        try {
            meetingUserService.updateMeetingUser(meetingUsers);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }
}
